package com.jiaai.cloud.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jiaai.cloud.base.exception.ServiceException;
import com.jiaai.cloud.base.page.FrontPage;
import com.jiaai.cloud.base.redis.util.RedisUtil;
import com.jiaai.cloud.base.util.IdGenerate;
import com.jiaai.cloud.base.util.JWTEncryptUtil;
import com.jiaai.cloud.base.util.MD5;
import com.jiaai.cloud.base.util.RestResultGenerator;
import com.jiaai.cloud.live.entity.TAnchor;
import com.jiaai.cloud.live.entity.TLiveBroadcast;
import com.jiaai.cloud.live.service.ITAnchorService;
import com.jiaai.cloud.live.service.ITLiveBroadcastService;
import com.jiaai.cloud.system.service.ITLiveServerService;
import com.jiaai.cloud.user.entity.TFollow;
import com.jiaai.cloud.user.entity.TUser;
import com.jiaai.cloud.user.entity.TUserWallet;
import com.jiaai.cloud.user.service.ITFollowService;
import com.jiaai.cloud.user.service.ITUserService;
import com.jiaai.cloud.user.service.ITUserWalletService;
import com.jiaai.cloud.utils.HttpHeaderUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 直播间api接口
 * </p>
 *
 * @author 佳爱网络科技
 * @version V1.0
 * @title BroadcastAPI
 * @since 2017/8/1
 */
@RequestMapping("/api/v1/broadcast")
@RestController
public class BroadcastAPI {
    @Autowired
    private ITLiveBroadcastService broadcastService;

    @Autowired
    private ITAnchorService anchorService;

    @Autowired
    private ITFollowService followService;
    @Autowired
    private ITUserService userService;

    @Autowired
    private ITUserWalletService userWalletService;

    @Autowired
    private ITLiveServerService liveServerService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 查找正在直播的房间
     * @return
     */
     @GetMapping("/list")
    public  Object findByBroadcastOnLive(FrontPage page)throws  ServiceException{
         try {

             return RestResultGenerator.genSuccessResult(broadcastService.findByBroadcastVo(page.getPagePlus()).getRows());
         }catch (Exception e){
            throw  new ServiceException("查询直播间失败",e.getMessage());
         }

    }

    /**
     * 开始直播
     * 生成推流token
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping("/start")
    public  Object start(@RequestBody  TLiveBroadcast broadcast, HttpServletRequest request)throws  Exception{
        TAnchor anchor=anchorService.selectOne(new EntityWrapper().eq("userId", HttpHeaderUtils.getUserId()));
        if(anchor==null){
            throw  new ServiceException("not anchor");
        }
        broadcast.setApp(IdGenerate.generateShortUuid());
        broadcast.setAnchorId(anchor.getAnchorId());
        broadcastService.insert(broadcast);
        String session_key=getSessionKey(broadcast);
        Map<String,String> dataMap=new HashMap<>();
        String url=liveServerService.getLiveUrl()+"/"+broadcast.getApp()+"?token="+session_key;
        dataMap.put("anchorId",broadcast.getAnchorId());
        dataMap.put("liveUrl",url);
        return RestResultGenerator.genSuccessResult(dataMap);
    }

    /***
     * 发送开播通知
     * @return
     */
    @GetMapping("/notify")
    public Object SendLiveNotify(){

        return "";
    }

    /**
     * 观看直播并生成token
     * 扣除相关费用
     * @param id
     * @return
     */
    @GetMapping("/play/{id}")
    public  Object getBroadcastInfo(@PathVariable("id")  String id)throws  ServiceException{
        TLiveBroadcast broadcast=broadcastService.selectById(id);
        if(broadcast.getPay()!=null){
            String userId="";
            try{
                userId=HttpHeaderUtils.getUserId();
            }catch (Exception e){
               throw  new ServiceException("收费房间请先登录!");
            }
            TUserWallet wallet=userWalletService.selectOne(new EntityWrapper().eq("userId",userId));
            if(wallet.getMoney().compareTo(BigDecimal.valueOf(broadcast.getPay()))==-1){
                 throw  new ServiceException("佘额不足,请充值");
            }
            wallet.setMoney(wallet.getMoney().subtract(BigDecimal.valueOf(broadcast.getPay())));
            try {
                userWalletService.insertOrUpdate(wallet);
            }catch (Exception e){
                throw  new ServiceException("扣费失败");
            }
        }
        if(broadcast==null){
            throw  new ServiceException("房间不存在");
        }
        Map<String,Object> dataMap=new HashMap();
        dataMap.put("session_key",getSessionKey(broadcast));

        return dataMap;
    }

    /**
     * 关注直播间
     * @param id 直播间Id
     * @return
     */
    @GetMapping("/follow/{id}")
    public  Object followAnchor(@PathVariable("id") String id)throws  ServiceException{
        TUser user=userService.getUserByBroadcastId(id);
        String formUserId="";
        try {
             formUserId=HttpHeaderUtils.getUserId();
        }catch (Exception e){
             throw  new ServiceException("未登录");
        }

        if(user==null){
            throw  new ServiceException("房间/主播不存在");
        }
        TFollow follow=new TFollow();
        follow.setFollowTime(new Date());
        follow.setUserId(user.getUserId());
        follow.setTargetId(formUserId);
        followService.insert(follow);
        return RestResultGenerator.genSuccessResult();

    }



    /**
     * 生成推流token
     * @param broadcast
     * @return
     * @throws ServiceException
     */
    private String getSessionKey(TLiveBroadcast broadcast)throws ServiceException{
        String key=new MD5().getMD5ofStr(broadcast.getAnchorId().toUpperCase()).toLowerCase();
        redisUtil.hashSet(0,"live",key, JSONObject.toJSONString(broadcast));
        return  key;
    }

}
